package com.ozo.boot.common.base.util;

/**
 * 命名转换工具类
 *
 * @author qiangesoft
 * @date 2024-05-23
 */
public class NamingConventionUtils {

    /**
     * 下划线命名法转为驼峰命名法
     *
     * @param underlineStr 下划线命名的字符串
     * @param smallCamel 是否使用小驼峰命名方式（首字母小写）
     * @return 驼峰命名的字符串
     */
    public static String underlineToCamel(String underlineStr, boolean smallCamel) {
        if (underlineStr == null || underlineStr.isEmpty()) {
            return "";
        }
        StringBuilder camelCaseStr = new StringBuilder();
        boolean toUpper = !smallCamel; // 如果需要小驼峰且是第一个字符，则不需要大写
        for (char c : underlineStr.toCharArray()) {
            if (c == '_') {
                toUpper = true; // 遇到下划线，则下一个字符需要大写
            } else {
                if (toUpper) {
                    camelCaseStr.append(Character.toUpperCase(c));
                    toUpper = false; // 已经大写，重置标志
                } else {
                    camelCaseStr.append(c);
                }
            }
        }
        // 如果需要小驼峰且字符串不为空，则将首字母转为小写
        if (smallCamel) {
            camelCaseStr.setCharAt(0, Character.toLowerCase(camelCaseStr.charAt(0)));
        }
        return camelCaseStr.toString();
    }

    /**
     * 驼峰命名法转为下划线命名法
     *
     * @param camelCaseStr 驼峰命名的字符串
     * @return 下划线命名的字符串
     */
    public static String camelToUnderline(String camelCaseStr) {
        if (camelCaseStr == null || camelCaseStr.isEmpty()) {
            return "";
        }
        StringBuilder underlineStr = new StringBuilder();
        for (int i = 0; i < camelCaseStr.length(); i++) {
            char c = camelCaseStr.charAt(i);
            if (Character.isUpperCase(c)) {
                if (i != 0) {
                    underlineStr.append('_');
                }
                underlineStr.append(Character.toLowerCase(c));
            } else {
                underlineStr.append(c);
            }
        }
        return underlineStr.toString();
    }

    // 测试方法
    public static void main(String[] args) {
        // 下划线转驼峰
        String underlineStr = "user_name_and_password";
        String camelCaseStr = underlineToCamel(underlineStr, false); // UserNameAndPassword
        System.out.println(camelCaseStr);

        camelCaseStr = underlineToCamel(underlineStr, true); // userNameAndPassword
        System.out.println(camelCaseStr);

        // 驼峰转下划线
        String testCamelCaseStr = "UserNameAndPassword";
        String testUnderlineStr = camelToUnderline(testCamelCaseStr); // user_name_and_password
        System.out.println(testUnderlineStr);
    }

}